import { memo, useEffect } from "react";
import { Drawer, Spin } from "antd";
import { propsType } from "../../config";
import { EditableProTable } from "@ant-design/pro-components";
import { cardColumnsConfig, cardType } from "./config";
import {
  useDeleteCard,
  useFetch_commitCard,
  useFetch_getCards,
} from "../../../../service/cards";

const Card = memo((props: propsType) => {
  const { id, open, close } = props;
  const { data, getLoading, refetch } = useFetch_getCards();
  const { commitCard, commitLoading } = useFetch_commitCard();
  const { deleteCard, delLoading } = useDeleteCard();
  useEffect(() => {
    if (id) {
      void refetch({
        courseId: id,
      });
    }
  }, [id]);

  const saveCard = (d: cardType) => {
    void commitCard(
      id!,
      {
        name: d.name,
        type: d.type,
        time: d.time,
        validityDay: Number(d.validityDay),
      },
      d.id
    ).then(() => {
      void refetch({
        courseId: id,
      });
    });
  };

  const onDeleteHandler = (key: string) => {
    void deleteCard(key).then(() => {
      void refetch({
        courseId: id,
      });
    });
  };

  return (
    <Drawer
      open={open}
      onClose={close as () => void}
      title="消费卡管理"
      width="50vw"
    >
      <Spin spinning={getLoading}>
        <EditableProTable
          loading={commitLoading || delLoading}
          rowKey="id"
          editable={{
            onSave(_row: number, data: cardType) {
              saveCard(data);
            },
            actionRender: (_row, _config, dom) => [dom.save, dom.cancel],
          }}
          recordCreatorProps={{
            position: "bottom",
            record: () => ({
              id: "new",
              name: "",
              time: 0,
              validityDay: 0,
              type: "time",
            }),
          }}
          value={data.toReversed()}
          columns={cardColumnsConfig(onDeleteHandler)}
        />
      </Spin>
    </Drawer>
  );
});

export default Card;
